package zeusees.tracking;

import android.content.Context;
import android.os.Environment;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * 脸部追踪工具类（HyperLandmark支持识别脸部106个特征点）
 */
public class FaceTracking {

    static {
        System.loadLibrary("zeuseesTracking-lib");
    }

    public native static void update(byte[] data, int height, int width, long session);

    public native static void initTracking(byte[] data, int height, int width, long session);

    public native static long createSession(String modelPath);

    public native static void releaseSession(long session);

    public native static int getTrackingNum(long session);

    public native static int[] getTrackingLandmarkByIndex(int index, long session);

    public native static int[] getTrackingLocationByIndex(int index, long session);

    public native static int getTrackingIDByIndex(int index, long session);

    private long session;
    //脸部特征集合
    private List<Face> faces;
    //模型文件存放路径
    private static final String modelPath = "/sdcard/ZeuseesFaceTracking/models";

    public FaceTracking(Context context) {
        initFaceModelFiles(context);
        session = createSession(modelPath);
        faces = new ArrayList<Face>();

    }

    protected void finalize() throws java.lang.Throwable {
        super.finalize();
        releaseSession(session);
    }

    public void FaceTrackingInit(byte[] data, int height, int width) {
        initTracking(data, height, width, session);

    }

    public void Update(byte[] data, int height, int width) {
        update(data, height, width, session);
        int numsFace = getTrackingNum(session);
        faces.clear();
        Log.d("numsFace_tracking", numsFace + "");

        for (int i = 0; i < numsFace; i++) {
            int[] landmarks = getTrackingLandmarkByIndex(i, session);
            int[] faceRect = getTrackingLocationByIndex(i, session);
            int id = getTrackingIDByIndex(i, session);
            Face face = new Face(faceRect[0], faceRect[1], faceRect[2], faceRect[3], landmarks, id);
            faces.add(face);
        }
    }

    /**
     * 获取追踪到的脸部信息
     *
     * @return
     */
    public List<Face> getTrackingInfo() {
        return faces;
    }

    /**
     * 拷贝assets里的文件到指定目录
     *
     * @param context
     * @param oldPath
     * @param newPath
     */
    private void copyFilesFromAssets(Context context, String oldPath, String newPath) {
        try {
            String[] fileNames = context.getAssets().list(oldPath);
            if (fileNames.length > 0) {
                File file = new File(newPath);
                if (!file.mkdir()) {
                    Log.d("mkdir", "can't make folder");
                }

                for (String fileName : fileNames) {
                    copyFilesFromAssets(context, oldPath + "/" + fileName,
                            newPath + "/" + fileName);
                }
            } else {
                InputStream is = context.getAssets().open(oldPath);
                FileOutputStream fos = new FileOutputStream(new File(newPath));
                byte[] buffer = new byte[1024];
                int byteCount;
                while ((byteCount = is.read(buffer)) != -1) {
                    fos.write(buffer, 0, byteCount);
                }
                fos.flush();
                is.close();
                fos.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 拷贝脸部模型文件到手机存储卡里
     *
     * @param context
     */
    private void initFaceModelFiles(Context context) {
        String assetPath = "ZeuseesFaceTracking";
        String sdcardPath = Environment.getExternalStorageDirectory()
                + File.separator + assetPath;
        copyFilesFromAssets(context, assetPath, sdcardPath);
    }

}
